package org.iot.iotserver;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.iot.iotserver.http.config.JettyServer;
import org.iot.iotserver.http.config.MyAnnotationConfiguration;
import org.iot.iotserver.netty.config.NettyServletContextBootstrapListener;
import org.iot.iotserver.netty.config.NettyTCPServer;

import javax.servlet.ServletContextEvent;

/**
 * 简单的 IOT Server 实现
 */
public class Application {

    private static final Log log = LogFactory.get();

    public static void main(String[] args) throws Exception {
        if(ArrayUtil.isEmpty(args) || args.length < 3) {
            log.error("启动参数配置错误");
            return;
        }

        // http 服务监听端口
        int httpServerPort = Integer.parseInt(args[0]);
        // netty 服务监听端口
        int nettyServerPort = Integer.parseInt(args[1]);
        // http 服务器资源根路径
        String resourceBase = args[2];

        // 构建 netty Server
        NettyTCPServer nettyTCPServer = new NettyTCPServer(nettyServerPort);
        // 让 netty Server 在 http 容器启动的时候启动
        NettyServletContextBootstrapListener nettyServletContextBootstrapListener = new NettyServletContextBootstrapListener() {
            @Override
            public void contextInitialized(ServletContextEvent servletContextEvent) {
                nettyTCPServer.start();
                super.contextInitialized(servletContextEvent);
            }
        };
        // 构建自定义注解扫描配置, 可以扫描到非 WEB-INFO/classes 目录下的 servlet3.0 注解类, 并注册到容器中
        AnnotationConfiguration annotationConfiguration = new MyAnnotationConfiguration();

        // 构建 httpServer
        JettyServer jettyServer = new JettyServer(httpServerPort);
        // 设置注解扫描配置类
        jettyServer.setAnnotationConfiguration(annotationConfiguration);
        // 设置启动监听类
        jettyServer.setServletContextListener(nettyServletContextBootstrapListener);
        // 设置 http 容器资源根路径
        jettyServer.setResourceBase(resourceBase);

        // 启动 http 容器
        jettyServer.start();
    }
}
